/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkTimerPool.h"
#include "MkTimer.h"
#include "MkUtil/MkUtil.h"
#include "MkUtil/MkLog.h"

CMkTimerPool::CMkTimerPool()
{

}

Uint32 CMkTimerPool::Start(Uint32 nCount/* = 0*/)
{
    if (0 == nCount) {
        CMkUtil::GetSystemCpuThreadNum(nCount);
    }
    Uint32 CurSize = m_VecTimer.size();
    //is started
    if (nCount == CurSize) {
        return NoneError;
    }
    for (Uint32 i = CurSize; i < nCount; i++) {
        CMkTimer *pTimer = new CMkTimer;
        if (!pTimer) {
            continue;
        }
        if (NoneError != pTimer->StartTimerThread()) {
            MkDelete(pTimer);
            continue;
        }
        m_VecTimer.emplace_back(pTimer);
    }
    return NoneError;
}

Uint32 CMkTimerPool::Stop()
{
    MkVector<CMkTimer*>::iterator it = m_VecTimer.begin();
    for (; it != m_VecTimer.end(); it++) {
        (*it)->StopTimerThread();
        MkDelete(*it);
    }
    m_VecTimer.clear();
    return NoneError;
}

CMkTimer* CMkTimerPool::GetFreeTimer()
{
    Uint32 MaxScore = 0;
    CMkTimer* pFreeTimer = nullptr;
    MkVector<CMkTimer*>::iterator it = m_VecTimer.begin();
    for (; it != m_VecTimer.end(); it++) {
        if (MaxScore < (*it)->GetScore()) {
            pFreeTimer = (*it);
            MaxScore = pFreeTimer->GetScore();
        }
    }
    //MkDebugLog("get free timer:%p\n", pFreeTimer);
    return pFreeTimer;
}

CMkTimerPool::~CMkTimerPool()
{
    Stop();
}